<template>
  <div>
    <el-form
      class="cards modal_form_content"
      :rules="rules"
      ref="ruleFormRef"
      :model="createCode"
      label-width="75"
      @validate="handleFormValidate"
    >
      <div style="display: flex; gap: 36px">
        <div style="display: flex; align-items: center; height: 28px">
          <el-form-item label="总编码数量:" class="form_text_item">
            <div style="line-height: 16px; color: #007cff; font-size: 14px">{{
              (createCode.qty = num)
            }}</div>
          </el-form-item>
        </div>
        <el-form-item
          required
          label="批次名称:"
          prop="name"
          :class="{ error_form_item: !formValidateResult['name'], form_input_item: true }"
        >
          <el-input
            maxlength="10"
            placeholder="请输入批次名称"
            v-model="createCode.name"
            class="input"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <div style="display: flex; align-items: center; height: 28px">
          <el-form-item label="编码类型:" class="form_radio_group_item">
            <el-radio-group v-model="createCode.type" @change="changeSwitch('')">
              <el-radio :value="1" size="large"> 成品</el-radio>
              <el-radio :value="2" size="large">配件</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </div>
      <div class="list">
        <div class="name">编码清单</div>
        <div class="text">支持多条产品型号批量创建</div>
      </div>
      <div class="table">
        <table>
          <thead>
            <tr>
              <th>商品型号<i class="fa fa-asterisk" aria-hidden="true"></i></th>
              <th>商品规格<i class="fa fa-asterisk" aria-hidden="true"></i></th>
              <th>编码数量<i class="fa fa-asterisk" aria-hidden="true"></i></th>
              <th>质保周期<i class="fa fa-asterisk" aria-hidden="true"></i></th>
              <th>
                <HPlainButton :height="20" :padding-lr="6" @click="addTypes()"
                  >增加型号</HPlainButton
                >
              </th>
            </tr>
          </thead>
          <tbody id="tbody" class="tbody">
            <tr v-for="(items, index) in createCode.codeVos" :key="index">
              <td>
                <el-select
                  v-model="items.goodsId"
                  class="part"
                  :filter-method="remoteMethod"
                  @focus="focusIndex(index)"
                  :loading="loading2"
                  remote-show-suffix
                  @change="chaneSelect(index, items.goodsId, '')"
                  placeholder="型号"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in items.options"
                    :key="item.id"
                    :value="item.id"
                    :label="item.model"
                  />
                </el-select>
              </td>
              <td>
                <el-select
                  v-model="items.goodsSpecId"
                  class="part"
                  :loading="loading3"
                  remote-show-suffix
                  :filter-method="remoteMethod3"
                  placeholder="规格"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in items.options2"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </el-select>
              </td>
              <td>
                <el-input
                  v-model="items.qty"
                  @input="items.qty = items.qty.replace(/[^0-9]/g, '')"
                  class="num-inp"
                />
              </td>
              <td>
                <el-input
                  v-model="items.warrantyDay"
                  @input="items.warrantyDay = items.warrantyDay.replace(/[^0-9]/g, '')"
                  class="num-inp"
                />
              </td>
              <td style="display: flex; align-items: center">
                <HLink type="error" @click="deleteType(index)">删除</HLink>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-form>
    <div class="btns" style="margin-bottom: 0; display: flex; gap: 10px">
      <HButton is-modal type="primary" @click="onaddSave(ruleFormRef)">保存</HButton>
      <HButton is-modal @click="changeCreate">取消</HButton>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { reactive, computed, ref, onMounted, watch } from 'vue'
  import {
    productPageSelect,
    productSpecPageSelect,
    sparePageSelect,
    spareSpecPageSelect,
    addSave,
  } from '@/api/code'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import * as _ from 'lodash'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'

  const emit = defineEmits(['close-popup', 'update-list'])

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService(['name'])

  const options = ref(null)
  const options2 = ref(null)
  const loading2 = ref(true)
  const loading3 = ref(false)
  const optId2 = ref()
  const optIndex = ref()
  const opt2Index = ref()
  const ruleFormRef = ref()

  const rules = reactive({
    name: [{ required: true, message: '请输入批次名称', trigger: 'blur' }],
  })
  const createCode = reactive({
    codeVos: [
      {
        goodsId: null, //商品ID
        goodsSpecId: null, //商品规格ID
        qty: '1', //生成编码数量
        warrantyDay: ' 1', //质保周期/天数
        options: [],
        options2: [],
      },
    ],
    name: '', //批次名称
    qty: 1, //编码数量
    type: 1, //编码类型：1-成品、2-配件
  })

  const num = computed(() => {
    let coun = 0
    createCode.codeVos.filter((o) => {
      coun += parseInt(o.qty)
    })
    return coun
  })
  onMounted(() => {
    changeSwitch('')
  })
  watch(
    () => createCode.type,
    () => {
      createCode.codeVos = [
        {
          goodsId: null, //商品ID
          goodsSpecId: null, //商品规格ID
          qty: '1', //生成编码数量
          warrantyDay: ' 1', //质保周期/天数
          options: null,
          options2: null,
        },
      ]
    },
  )
  // 增加型号
  const addTypes = () => {
    let tmp = {
      goodsId: null, //商品ID
      goodsSpecId: null, //商品规格ID
      qty: ' 1', //生成编码数量
      warrantyDay: '1', //质保周期/天数
      options: options.value,
      options2: null,
    }
    createCode.codeVos.push(tmp)
  }
  // 删除型号
  const deleteType = (val) => {
    createCode.codeVos = createCode.codeVos.filter((o, index) => index != val)
  }
  const changeCreate = () => {
    resetFormValidateResult()
    emit('close-popup', false)
  }
  const focusIndex = (val) => {
    opt2Index.value = val
  }
  const remoteMethod = _.throttle((val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (createCode.type == 1) {
      productPageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[opt2Index.value].options = options.value
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
      })
    } else {
      sparePageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[opt2Index.value].options = options.value
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
      })
    }
  }, 500)
  const remoteMethod3 = _.throttle((val: string) => {
    if (val) {
      createCode.codeVos[optIndex.value].options2 = null
    }
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (!optId2.value) {
      return
    }
    if (createCode.type == 1) {
      productSpecPageSelect(data, optId2.value).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
          createCode.codeVos[optIndex.value].options2 = options2.value
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
        loading3.value = false
      })
    } else {
      spareSpecPageSelect(data, optId2.value).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
          createCode.codeVos[optIndex.value].options2 = options2.value
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
        loading3.value = false
      })
    }
  }, 500)
  const changeSwitch = async (val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (createCode.type == 1) {
      await productPageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[0].options = options.value
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
      })
    } else {
      await sparePageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[0].options = options.value
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
      })
    }
  }
  const chaneSelect = async (index, id, val) => {
    optId2.value = id
    optIndex.value = index
    createCode.codeVos[index].goodsSpecId = null
    createCode.codeVos[index].options2 = null
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (!id) {
      return
    }
    if (createCode.type == 1) {
      await productSpecPageSelect(data, id).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
        loading3.value = false
      })
    } else {
      await spareSpecPageSelect(data, id).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 3000,
            })
        }
        loading3.value = false
      })
    }
    createCode.codeVos[index].options2 = options2.value
  }
  // 保存
  const onaddSave = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        let data = _.cloneDeep(createCode)
        data.codeVos = data.codeVos.map((o) => {
          delete o.options
          delete o.options2
          return o
        })
        let goodsId = data.codeVos.some((o) => {
          return !o.goodsId
        })
        let goodsSpecId = data.codeVos.some((o) => {
          return !o.goodsSpecId
        })
        if (goodsId) {
          ElMessage({
            showClose: true,
            message: '请选择商品型号',
            type: 'error',
            duration: 3000,
          })
          return
        }
        if (goodsSpecId) {
          ElMessage({
            showClose: true,
            message: '请选择商品规格',
            type: 'error',
            duration: 3000,
          })
          return
        }

        addSave(data).then((res) => {
          if (res.data.code == 20000) {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'success',
              duration: 3000,
            })
            changeCreate()
            emit('update-list')
          } else {
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 3000,
              })
          }
        })
      }
    })
  }
</script>
<style lang="scss" scoped>
  @import './index.scss';
</style>
